﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Collections;
using System.Xml.Linq;

namespace Sofire.Data.XSql
{
    internal class XSqlSwitchNode : XSqlTestNodeBase, IXSqlSwitchNode
    {
        public const string NodeName = "switch";

        public override XSqlType Type
        {
            get { return XSqlType.Switch; }
        }

        public override XObject CreateXObject()
        {
            return CreateXTest(NodeName);
        }

        public override string Compile(XSqlParameterCollection parameters)
        {
            var test = this.GetTest(parameters);
            IXSql node = null;
            foreach(var item in this.Children)
            {
                if(item.Type == XSqlType.Case)
                {
                    XSqlCaseNode caseNode = item as XSqlCaseNode;
                    caseNode.TestPrefix = test;
                    if(caseNode.CompileTest(parameters))
                    {
                        node = item;
                        break;
                    }
                }
                else if(item.Type == XSqlType.Default)
                {
                    node = item;
                    break;
                }
                else this.ThrowException(XSqlError.Invalid, XSqlAttributes.Children);

            }
            if(node == null) return null;
            return node.Children.Compile(parameters);
        }
    }

    internal class XSqlCaseNode : XSqlTestNodeBase, IXSqlCaseNode
    {
        public const string NodeName = "case";
        public override XSqlType Type
        {
            get { return XSqlType.Case; }
        }

        public override XObject CreateXObject()
        {
            return CreateXTest(NodeName);
        }

        public override string Compile(XSqlParameterCollection parameters)
        {
            return null;
        }
    }

    internal class XSqlDefaultNode : XSqlNodeBase, IXSqlDefaultNode
    {
        public const string NodeName = "default";
        public override XSqlType Type
        {
            get { return XSqlType.Default; }
        }

        public override XObject CreateXObject()
        {
            XElement element = new XElement(NodeName);
            this.CreateXChildren(element);
            return element;
        }

        protected override void Load(XmlNode node) { }

        public override string Compile(XSqlParameterCollection parameters)
        {
            return null;
        }
    }
}
